import { useEffect, useState } from 'react';
import { Button, Col, Form, Input, Popconfirm, Row, Space, Table } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { Role, QueryRoleListParams } from './services';
import { queryRoleList, delRole } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import { jump2target } from '@/utils/common';

const RolePage: React.FC = () => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<QueryRoleListParams>()
  const [searchParams, setSearchParams] = useState<QueryRoleListParams>({
    pageNum: 1, pageSize: 10,
  });
  const roleList = useRequest(() => queryRoleList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delRoleAsync } = useRequest(delRole, {manual: true})

  const onFinish = (formValues: QueryRoleListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const openEditPage = (title: string, type: string, roleId?: number) => {
    jump2target(`/system/roleList/edit?type=${type}&id=${roleId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/system/roleList/edit_title', title)
  }

  const columns: ColumnsType<Role> = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      width: 120,
    },
    {
      title: '角色描述',
      dataIndex: 'commend',
      width: 120,
      render: val => val || '--'
    },
    {
      title: '权限功能',
      key: 'auth',
      width: 120,
      render: (_, record) => <a onClick={() => openEditPage('角色详情', 'look', record.id)}>查看</a>
    },
    {
      title: '操作',
      key: 'operation',
      width: 100,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <Access accessible={access.编辑 || true}>
            <a onClick={() => openEditPage('编辑角色', 'edit', record.id)}>编辑</a>
          </Access>
          <Access accessible={access.删除 || true}>
            <Popconfirm
              title={`确定删除角色: ${record.roleName} 吗?`}
              onConfirm={() => delRoleAsync({roleId: record.id}).then(roleList.refresh)}
              okText="删除"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </Access>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      roleList.refresh()
    }
    window.addEventListener('refreshRoleList', refresh)
    return () => {
      window.removeEventListener('refreshRoleList', refresh)
    }
  }, []);
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加角色', 'edit')}>添加角色</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchRoleForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='角色名称' name='roleName'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={roleList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Role>
          rowKey='id'
          loading={roleList.loading}
          dataSource={roleList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: roleList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default RolePage;
